package com.security.springsecurity02.config;

import com.security.springsecurity02.handler.MyAccessDeniedHandler;
import com.security.springsecurity02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

//@Configuration
public class WebConfig extends WebSecurityConfigurerAdapter {



    @Autowired
    private UserService userService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();
        http.authorizeRequests()
                .antMatchers(HttpMethod.GET, "/admin/demo").permitAll()
                //具有admin的权限才能访问
                .antMatchers("/admin/main").hasAnyAuthority("a1", "a2")
                //具有user的角色才能访问
                .antMatchers("/admin/query").hasRole("r1")
                .antMatchers("/admin/test").hasAnyRole("r1", "r2")
                //只要是js都放行 ** 代表目录 * 代表任意的字符
                .antMatchers("/**/*.js").permitAll()
                //也可以使用正则表达式
                .regexMatchers(".+[.]jpg").permitAll();


        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler());

        http.authorizeRequests().anyRequest().authenticated();
        http.csrf().disable();
        http.userDetailsService(userService);

    }
}
